const { app } = require('electron');
const fs = require('fs')
import { join } from "path"

// 获取应用程序的根目录
// const appPath = app.getAppPath();
const designPath = app.getPath('documents')

let proxyJsonPath = join(designPath, './proxy.json')

const addDataToJsonFile = (data: string) => {
  return new Promise((resolve, _reject)=> {
    console.log(proxyJsonPath)
    fs.writeFile(proxyJsonPath, data, 'utf-8',(err)=> {
      if(err){
        resolve('error:写入失败')
      }else{
        resolve('')
      }
    })
  })
}

export const writeProxyFileData = (data: string) => {
  const exists = fs.existsSync(proxyJsonPath);
  return new Promise(async (resolve, _reject)=> {
    if(exists){
      fs.truncate(proxyJsonPath, 0, (err) => {
        if (err) {
          resolve('error:清空内容失败')
          return
        };
        // 写入数据
        let res = addDataToJsonFile(data)
        resolve(res)
      });
    }else{
      let res = addDataToJsonFile(data)
      resolve(res)
    }
  })
}

// 读取文件内容
export const readProxyFileData = () => {
  const exists = fs.existsSync(proxyJsonPath);
  return new Promise((resolve, _reject)=> {
    if(exists){
      fs.readFile(proxyJsonPath, 'utf8', (err, data) => {
        if (err) {
          resolve('error:读取内容失败')
          return
        };
        resolve(JSON.parse(data))
      });
    }else{
      resolve([])
    }
  })
}